package com.atguigu.spzx.product.service.Impl;

import com.atguigu.spzx.model.entity.product.Category;
import com.atguigu.spzx.product.mapper.CategoryMapper;
import com.atguigu.spzx.product.service.CategoryService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author LT
 * @create 2024-03-25-19:18
 */
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper,Category> implements CategoryService {

    @Resource
    CategoryMapper categoryMapper;

    @Override
    @Cacheable(value = "spzx:findCategoryTree",key = "'CategoryTre'",unless = "#result.size()==0")
    public List<Category> findCategoryTree() {

//        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
//        queryWrapper.eq(Category::getParentId,0);
//        List<Category> parents = categoryMapper.selectList(queryWrapper);
        List<Category> categories = categoryMapper.selectList(null);
        List<Category> parents = categories.stream().filter(category -> category.getParentId().longValue() == 0L).collect(Collectors.toList());
        buildCategoryTree(parents,categories);
        return parents;
    }

    private void buildCategoryTree(List<Category> parents, List<Category> categories) {

        if (CollectionUtils.isEmpty(parents)){
            return;
        }

        parents.forEach(parent ->{
            List<Category> children = categories.stream()
                    .filter(category -> category.getParentId().longValue() == parent.getId())
                    .collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(children)){
                parent.setHasChildren(true);
                parent.setChildren(children);
                //有子集先遍历装配，再返回。
                buildCategoryTree(children,categories);
            }
        });

    }
}
